import { FC, useContext, useRef, useState } from 'react';
import { HotTable, HotColumn } from '@handsontable/react';
import zhCN from 'handsontable/languages/zh-CN';

import styles from './index.less';
import 'handsontable/dist/handsontable.full.css';

const TableFC: FC<any> = (props: any) => {
  const { property } = props;

  const hotTableComponent = useRef(null);

  const hotSettings = property.comProperty;
  hotSettings.language = zhCN; // 添加语言
  const afterSetCellMeta = (
    row: number,
    col: number,
    key: string,
    value: any,
  ) => {
    // console.log(
    //   'row: number, col: number, key: string, value: any',
    //   row,
    //   col,
    //   key,
    //   value,
    // );
  };

  // 个或多个单元格的值被改变后调用
  const afterChange = (changes: Array<any>, source: string) => {
    if (source === 'edit' && changes && changes.length > 0) {
      for (const cItem of changes) {
        const rowIndex = cItem[0];
        const colIndex = cItem[1];
        const newItem = cItem[3];
        hotSettings.data[rowIndex][colIndex] = newItem;
      }
    }
  };

  // 行高改变后调用
  const afterRowResize = (size: number, row: number) => {
    hotSettings.rowHeights[row] = size;
  };

  // 行合并
  const afterMergeCells = (cellRange, mergeParent) => {
    let status = true;
    for (let item of hotSettings.mergeCells) {
      if (item.row == mergeParent.row && item.col == mergeParent.col) {
        status = false;
      }
    }
    hotSettings.mergeCells.push(mergeParent);
  };

  // 列列改变后调用
  const afterColumnResize = (size: number, col: number) => {
    hotSettings.colWidths[col] = size;
  };

  /**
   * 当一个或多个单元格被选中后调用
   * @param r 选中的单元格起始行
   * @param c 选中的单元格的起始列
   * @param r2 选中单元格的终止行
   * @param c2 选中的单元格的终止列
   */

  // todo 修改单个属性
  const afterSelection = (r: number, c: number, r2: number, c2: number) => {
    console.log('r: number, c: number, r2: number, c2: number', r, c, r2, c2);
  };

  // 表格合并
  const beforeCellAlignment = (range, type, alignmentClass) => {
    let cellArr = [];
    // 计算对齐的表格
    if (type && type[0]) {
      const { from, to } = type[0];
      for (let fRowIndex = from.row; fRowIndex <= to.row; fRowIndex++) {
        for (let fColIndex = from.col; fColIndex <= to.col; fColIndex++) {
          cellArr.push({
            row: fRowIndex,
            col: fColIndex,
            className: [range[fRowIndex][fColIndex], alignmentClass].join(' '),
          });
        }
      }
    }

    // 去掉重复
    let newCell = [];
    for (let sCell of hotSettings.cell) {
      let status = true;
      for (let aCell of cellArr) {
        // 判断是否有是否做最新更改
        if (sCell.row == aCell.row && sCell.col == aCell.col) {
          status = false;
        }
      }
      if (status) {
        newCell.push(sCell);
      }
    }

    hotSettings.cell = [...newCell, ...cellArr];
  };

  // 添加行
  // todo 计算行合并的内容
  const afterCreateCol = (index: number, amount: number) => {
    console.log(index, amount);
  };

  // 插入行
  const afterCreateRow = (index: number, amount: number) => {
    const { mergeCells } = hotSettings;
    let newCell = mergeCells.map((item) => {
      const { row } = item;
      if (row >= index) {
        item.row += 1;
      }
      return item;
    });
    hotSettings.mergeCells = newCell;
  };

  //
  const afterOnCellMouseDown = (event, coords, td) => {
    console.log('coords,td', coords, td);
  };

  return (
    <div className={styles.ztTable}>
      <HotTable
        ref={hotTableComponent}
        language={'zh-CN'}
        className="custom-table-xxx"
        afterChange={afterChange}
        afterRowResize={afterRowResize}
        afterSetCellMeta={afterSetCellMeta}
        afterColumnResize={afterColumnResize}
        afterMergeCells={afterMergeCells} // 单元格合并
        afterSelection={afterSelection} // 当一个或多个单元格被选中后调用
        beforeCellAlignment={beforeCellAlignment} // 表格对齐之前
        afterCreateCol={afterCreateCol} // 添加列
        afterCreateRow={afterCreateRow} // 添加行
        afterOnCellMouseDown={afterOnCellMouseDown} // 点击单元格或行头/列头后被调用
        // colHeaders={true}
        // rowHeaders={true}
        settings={hotSettings}
        licenseKey={'non-commercial-and-evaluation'}
        width={hotSettings.width}
        height={'auto'}
        manualColumnResize={true}
        manualRowResize={true}
        rowHeaders={true}
        contextMenu={[
          'row_above',
          'row_below',
          'col_left', // 左插入
          'col_right', // 右插入
          'remove_col', // 删除
          'alignment', // 对齐
          'mergeCells', //合并
        ]}
        // height="300"
      />
    </div>
  );
};

export default TableFC;
